const { app, BrowserWindow, ipcMain, dialog } = require('electron');
const path = require('path');
const fs = require('fs');

let mainWindow;

function createWindow() {
    mainWindow = new BrowserWindow({
        width: 1200,
        height: 800,
        resizable: false,
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false
        }
    });

    mainWindow.loadFile(path.join(__dirname, 'src', 'index.html'));
    
    // 等待窗口加载完成后发送初始文件列表
    mainWindow.webContents.on('did-finish-load', () => {
        // 读取文件并直接发送到渲染进程
        const dirPath = path.join(__dirname, 'ID');
        if (!fs.existsSync(dirPath)) {
            fs.mkdirSync(dirPath);
        }
        
        const files = fs.readdirSync(dirPath)
            .flatMap(folder => {
                const folderPath = path.join(dirPath, folder);
                return fs.readdirSync(folderPath)
                    .filter(file => file.endsWith('.json') && file !== 'skillpoint.json')
                    .map(file => ({
                        name: file,
                        path: path.join(folderPath, file)
                    }));
            });
        
        mainWindow.webContents.send('id-created', { files });
    });
}

// 在应用启动时读取文件
app.whenReady().then(() => {
    createWindow();
});

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit();
    }
});

// 处理新建ID请求
ipcMain.on('create-new-id', (event, newId) => {
    const now = new Date();
    const timestamp = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}`;
    const idFolderName = `${timestamp}_${newId}`;
    const idFolderPath = path.join(__dirname, 'ID', idFolderName);
    
    // 创建ID文件夹
    fs.mkdirSync(idFolderPath, { recursive: true });

    // 创建子文件夹
    const subFolders = ['projects', 'thoughts', 'compositions'];
    subFolders.forEach(folder => {
        fs.mkdirSync(path.join(idFolderPath, folder), { recursive: true });
    });

    // 复制assistant.md文件
    const assistantSrcPath = path.join(__dirname, 'assistant.md');
    const assistantDestPath = path.join(idFolderPath, 'assistant.md');
    if (fs.existsSync(assistantSrcPath)) {
        fs.copyFileSync(assistantSrcPath, assistantDestPath);
    }

    // 创建空的skillpoint.json文件
    const skillpointPath = path.join(idFolderPath, 'skillpoint.json');
    fs.writeFileSync(skillpointPath, JSON.stringify({ attributes: [] }, null, 2), 'utf8');

    // 生成JSON文件
    const jsonFilePath = path.join(idFolderPath, `${timestamp}.json`);
    fs.writeFileSync(jsonFilePath, JSON.stringify({ ID: newId }, null, 2), 'utf8');
    
    // 创建完成后触发读取
    ipcMain.emit('load-json-files', event);
});

// 处理读取请求
ipcMain.on('load-json-files', (event) => {
    const dirPath = path.join(__dirname, 'ID');
    if (!fs.existsSync(dirPath)) {
        fs.mkdirSync(dirPath);
    }
    
    const files = fs.readdirSync(dirPath)
        .flatMap(folder => {
            const folderPath = path.join(dirPath, folder);
            return fs.readdirSync(folderPath)
                .filter(file => file.endsWith('.json') && file !== 'skillpoint.json')
                .map(file => ({
                    name: file,
                    path: path.join(folderPath, file)
                }));
        });
    
    event.reply('id-created', { files });
});

// 读取单个JSON文件内容
ipcMain.handle('read-json-file', async (event, filePath) => {
    const content = fs.readFileSync(filePath, 'utf8');
    return JSON.parse(content);
});

// 处理从指定目录读取文件的请求
ipcMain.handle('get-files-from-directory', async (event, directoryPath) => {
    try {
        if (!fs.existsSync(directoryPath)) {
            return [];
        }
        
        const files = fs.readdirSync(directoryPath)
            .filter(file => file.endsWith('.json') && file !== 'skillpoint.json')
            .map(file => ({
                name: file,
                path: path.join(directoryPath, file)
            }));
        return files;
    } catch (error) {
        console.error('Error reading directory:', error);
        return [];
    }
});

// 添加新的IPC处理器用于打开文件或URL
ipcMain.handle('open-file-or-url', async (event, path, type) => {
    const { shell } = require('electron');
    try {
        if (type === 'url') {
            await shell.openExternal(path);
            return { success: true };
        } else {
            if (type === 'executable') {
                require('child_process').exec(path);
                return { success: true };
            } else if (type === 'text') {
                const content = fs.readFileSync(path, 'utf8');
                return { success: true, content };
            } else {
                await shell.showItemInFolder(path);
                return { success: true };
            }
        }
    } catch (error) {
        return { success: false, error: error.message };
    }
});

// 添加新的IPC处理器用于保存属性
ipcMain.handle('save-attribute', async (event, { filePath, attribute }) => {
    try {
        // 从filePath中获取ID文件夹路径
        const idFolderPath = path.dirname(filePath);
        const skillpointPath = path.join(idFolderPath, 'skillpoint.json');

        let data = { attributes: [] };
        if (fs.existsSync(skillpointPath)) {
            const content = fs.readFileSync(skillpointPath, 'utf8');
            data = JSON.parse(content);
        }

        data.attributes = data.attributes || [];
        data.attributes.push(attribute);
        fs.writeFileSync(skillpointPath, JSON.stringify(data, null, 2), 'utf8');
        return { success: true, data };
    } catch (error) {
        console.error('Error saving attribute:', error);
        return { success: false, error: error.message };
    }
});

// 添加新的IPC处理器用于保存项目
ipcMain.handle('save-project', async (event, { filePath, project }) => {
    try {
        // 确保projects目录存在
        const projectsDir = path.dirname(filePath);
        if (!fs.existsSync(projectsDir)) {
            fs.mkdirSync(projectsDir, { recursive: true });
        }

        // 保存项目数据
        fs.writeFileSync(filePath, JSON.stringify(project, null, 2), 'utf8');
        return { success: true };
    } catch (error) {
        console.error('Error saving project:', error);
        return { success: false, error: error.message };
    }
}); 